'use strict';

angular.module('webDevApp')
  .controller('MainCtrl', ['$scope', '$http', 'CartService','AuthService',function ($scope, $http, CartService, AuthService) {
  	$scope.cart = CartService.getCart();

  	$scope.$watch('cart', function(){
  		console.log('cart changed');
  		$scope.price = CartService.getTotal();
  	}, true);

  	$scope.logout = function(){
  		AuthService.logout();
  	}
  }])
  .controller('HomeController', ['$scope', '$rootScope','$http', 'CartService',function ($scope, $rootScope, $http, CartService) {

  	$scope.searchTerm = '';

  	$scope.images = [];

  	var api_key = '62177fa5492936ad951e32f185840815';

    $scope.$watch('searchTerm', function (newVal) {
       if(newVal !== ''){
       	console.log('Searching for '+newVal);
	    	var tags = newVal;
	    	var URL = 'https://api.flickr.com/services/rest/?&method=flickr.photos.search&tags='+tags+'&api_key='+api_key+'&format=json&nojsoncallback=1&per_page=10&extras=tags';
 			$scope.loading = true;
	    	$http.get(URL).success(function(data){
	    		$scope.loading = false;
	    		console.log('Finished');
	    		$scope.images = data.photos.photo;
	    		console.log($scope.images);
	    	});
        }
    });

    $scope.addToCart = function(){
    	angular.forEach($scope.images, function(image){
    		if(image.selected === true){
    			CartService.add(image);
    			image.selected = false;
    		}
    	});
    	console.log(CartService.getCart());
		$http.post('savecart', CartService.getCart()).success(function(){

		}).error(function(){
			alert('Could not contact server');
		});
    }
}])
.controller('CartController',['$scope','$http','CartService',function($scope, $http, CartService){
  	$scope.cart = CartService.getCart();

  	$scope.removeItem = function(id){
  		CartService.remove(id);
  		$scope.cart = CartService.getCart();
		$http.post('savecart', $scope.cart).success(function(){
		}).error(function(){
			alert('Could not contact server');
		});
  	}
  }])
.controller('CheckoutController', ['$scope','$http','CartService',function($scope, $http, CartService){

	$scope.total = 0;

	$scope.getTotal = function(){

		$http.post('checkoutshipping', {city: $scope.city}).success(function(total){
			$scope.total = total.shippingcost;
		}).error(function(){
			alert('Could not contact server');
		});
		$scope.total = 234;
	}

	$scope.commit = function(){
		if($scope.total == 0)
			alert('Please calculate the shipping cost to complete your order');
		$http.get('finalcheckout').success(function(data){
			alert('Bought!');
			CartService.empty();
		}).error(function(){
			alert('Could not contact server');
		});
	}
}])
.controller('OrdersController', [function($scope){

}])
.controller('AdminController', ['$scope','$http','orders', function($scope, $http, orders){
	$scope.orders = orders.data;
	console.log(orders)
	// $scope.orders = [{id:3, status:'PENDING'}, {id:4, gsdfg:'g'}];
	$scope.vals = [
		{ 'value': 'PENDING', 'name': 'Pending' },
		{ 'value': 'COMPLETE', 'name': 'Complete' },
	];
	$scope.updateOrderStatus = function(id, status){
		$http.post('updatestatus', {id: id, status:status}).success(function(total){
			$scope.total = total;
		}).error(function(){
			alert('Could not contact server');
		});
	}
}])
.controller('LoginController', ['$scope','$state','AuthService',function($scope, $state, AuthService){
	$scope.details = {};
	$scope.login = function(){
		console.log('Loggin in..');
		AuthService.login($scope.details, function(user){
			if(!user){
				$scope.error = 'Incorrect username or password';
			}else{
				$state.transitionTo('home');
			}
		});
	}
}])
.factory('CartService', ['$http',function($http){
	var cart = []

	return {
		add: function(item){
			cart.push(item);
			console.log(JSON.stringify(cart));

		},
		remove: function(itemId){
			var i = cart.length;
		    while(i--){
		       if(cart[i].id === itemId){
		           cart.splice(i,1);
		       }
		    }
		    console.log(cart);
		},
		getCart: function(){
			return cart;
		},
		getTotal: function(){
			var total = 0;
			angular.forEach(cart, function(item){
				total = total + item.tags.split(' ').length;
			})
			return total;
		},
		empty: function(){
			cart = [];
		}
	}
}])
.factory('AuthService', ['$http','$rootScope',function($http, $rootScope){
	// $rootScope.user = null;
	console.log($rootScope.user);
	return {
		login: function(details, callback){
			$http.post('userlogin', details).success(function(data){
				console.log('Successful login - returned user data: '+data);
				$rootScope.user = data;
				window.user = JSON.stringify(data);
				callback(data);
			}).error(function(){
				callback();
			})
		},
		logout: function(){
			$http.get('userlogout').success(function(data){
				console.log('Successful logout');
				$rootScope.user = null;
				window.user = null;
				callback(data);
			}).error(function(){
				callback();
			})
		}
	}
}])
.filter('cut', function () {
        return function (value, wordwise, max, tail) {
            if (!value) return '';

            max = parseInt(max, 10);
            if (!max) return value;
            if (value.length <= max) return value;

            value = value.substr(0, max);
            if (wordwise) {
                var lastspace = value.lastIndexOf(' ');
                if (lastspace != -1) {
                    value = value.substr(0, lastspace);
                }
            }

            return value + (tail || ' …');
        };
    });;
